import 'dart:convert';
import 'package:app/util/WebSocketInheritedWidget.dart';
import 'package:flutter/material.dart';
import '../../components/index.dart';
import '../../api/account/index.dart';
import '../../util/SecureStorage.dart';
import '../../util/WebSocketManager.dart';
import '../../util/StringUtils.dart';
import '../../api/dictionary/index.dart';

class Login extends StatefulWidget {
  const Login({super.key});

  @override
  State<Login> createState() => _LoginState();
}

/// 登录页面
class _LoginState extends State<Login>{

  String _userName = "";

  String _password = "";

  bool _checked = false;

  final FocusNode _userNameFocusNode = FocusNode();

  final FocusNode _passwordFocusNode = FocusNode();

  final GlobalKey<FormState>? _formKey = GlobalKey<FormState>();

  late WebsocketManager _socket;

  @override
  void initState() {
    SecureStorage().get("loginInfo").then((res) => init(res));
    super.initState();
  }

  init(res){
    if(StringUtils.isNotNull(res)){
      setState(() {
        dynamic result = jsonDecode(res);
        _userName = result["userName"];
        _password = result["password"];
        _checked = true;
        // sendLoginRequest();
      });
    }
  }

  login() {
    Forms.validate(_formKey!).then((valid){
      if(valid){
        sendLoginRequest();
      }
    });
  }

  sendLoginRequest(){
    SecureStorage.of().remove("token");
    Account.of(context).login(_userName, _password).then((res) => res != null ? connectSocket(res) : '');
  }

  connectSocket(res){
    String userId = res.data['data']['userId'].toString();
    _socket = WebsocketManager(userId: userId, device: "0");
    _socket.connection();
    _socket.messageStream.listen((data) => loginSuccess(data, res));
    WebSocketInheritedWidget.of(context)?.socket = _socket;
  }

  loginSuccess(message, res){
    if(message['eventName'] == '__login_success'){
      SecureStorage().set("token", res.data['data']['token']);
      _checked ? SecureStorage().set("loginInfo",
          jsonEncode({"userName": _userName, "password": _password})) : '';
      loadDictionary();
      setAccount(res);
      Navigator.pushNamed(context, "/home");
    }
  }

  setValue(dynamic value, String key) async{
    return setState(() {
      switch(key){
        case "_userName": _userName = value; _userNameFocusNode.requestFocus(); break;
        case "_password": _password = value; _passwordFocusNode.requestFocus(); break;
        case "_checked": SecureStorage.of().remove("loginInfo"); _checked = value; break;
        default: throw Exception("key error");
      }
    });
  }

  /// 加载字典
  loadDictionary(){
    String types = Dictionary.type.keys.map((key) => Dictionary.type[key]).toString()
        .trim().replaceAll(RegExp(r'\s|\(|\)'), '');
    Dictionary.of(context).listByTypes(types).then((res) => SecureStorage.of().set("dictionary", jsonEncode(res.data['data'])));
  }

  @override
  void dispose() {
    // _socket?.disconnect();
    super.dispose();
  }

  /// 设置账号信息到缓存
  void setAccount(res){
    String userName = res.data['data']['userName'];
    dynamic user = {'account': _userName, 'password': _password, 'userName': userName};
    // SecureStorage.of().remove('accounts');
    SecureStorage.of().get('accounts').then((account){
      if(StringUtils.isNotNull(account)){
        List<dynamic> accounts = jsonDecode(account);
        bool flag = accounts.any((item) => item['account'] == _userName);
        if(!flag){
          SecureStorage.of().set('accounts', jsonEncode([...accounts, user]));
        }
      }else{
        SecureStorage.of().set('accounts', jsonEncode([user]));
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomInset: false,
        body: Container(
          width: MediaQuery.of(context).size.width,
          height: MediaQuery.of(context).size.height,
          child: Column(
            children: [
              const Padding(
                padding: EdgeInsets.only(top: 50),
                child: Image(
                  image: AssetImage("assets/image/logo.png"),
                  width: 250,
                ),
              ),
              Padding(
                padding: const EdgeInsets.only(left: 16.0, right: 16, top: 20),
                child: Forms(
                  formKey: _formKey,
                  formItem: <FormItem>[
                    FormItem(
                      focusNode: _userNameFocusNode,
                      type: 'inputText',
                      labelText: '用户名',
                      value: _userName,
                      filedName: 'userName',
                      icon: const Icon(Icons.person),
                      onChange: (value) => setValue(value, '_userName'),
                      rules: const {'userName': [{'required': true, 'message': '用户名不能为空'}]},
                    ),
                    FormItem(
                      focusNode: _passwordFocusNode,
                      type: 'password',
                      labelText: '密码',
                      filedName: 'password',
                      value: _password,
                      icon: const Icon(Icons.lock),
                      onChange: (value) => setValue(value, '_password'),
                      rules: const {'password': [{'required': true, 'message': '密码不能为空'}]},
                    ),
                    FormItem(
                        rowSpacing: 5,
                        type: 'checkbox',
                        checked: _checked,
                        labelText: '记住密码',
                        onChange: (value) => setValue(value, "_checked")
                    ),
                    FormItem(
                      type: 'button',
                      rowSpacing: 5,
                      labelText: '登录',
                      height: 50,
                      fontSize: 18,
                      onClick: login,
                    ),
                  ],
                ),
              ),
            ],
          ),
        )
    );
  }
}
